package com.zzyl.nursing.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.service.ICheckInService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 入住Service业务层处理
 *
 * @author yuanjijun
 * @date 2025-07-25
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    @Autowired
    private ContractMapper contractMapper;

    @Transactional
    @Override
    public void apply(CheckInApplyDto checkInApplyDto) {
        //1、老人已经存在并且是非0/5
        String idCardNo = checkInApplyDto.getCheckInElderDto().getIdCardNo();//老人身份证号码
        Elder elder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery().eq(Elder::getIdCardNo, idCardNo));
        if (elder != null && elder.getStatus() != 0 && elder.getStatus() != 5) {
            throw new BaseException("老人已入住！");
        }

        //2、老人不存在，占用床位，status-1
        int count = bedMapper.updateBedStatus(checkInApplyDto.getCheckInConfigDto().getBedId());

        //3、新增或修改老人信息
        Bed bed = bedMapper.selectById(checkInApplyDto.getCheckInConfigDto().getBedId());
        elder = insertOrUpdate(checkInApplyDto, elder, bed);

        //4、新增签约办理
        insertContract(checkInApplyDto, elder);
        
        //5、新增入住
        CheckIn checkIn = insertCheckIn(checkInApplyDto, elder, bed);

        //6、新增入住配置
        insertCheckInConfig(checkInApplyDto, checkIn);
    }

    /****
     * 新增入住配置
     * @param checkInApplyDto
     * @param checkIn
     */
    private void insertCheckInConfig(CheckInApplyDto checkInApplyDto, CheckIn checkIn) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInConfigDto(),checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insert(checkInConfig);
    }


    /***
     * 新增入住信息
     * @param checkInApplyDto
     * @param elder
     * @param bed
     * @return
     */
    private CheckIn insertCheckIn(CheckInApplyDto checkInApplyDto, Elder elder, Bed bed) {
        CheckIn checkIn = new CheckIn();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInConfigDto(),checkIn);
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setBedNumber(bed.getBedNumber());
        checkIn.setStatus(1);
        checkIn.setCreateTime(new Date());
        checkIn.setRemark(JSONUtil.toJsonStr(checkInApplyDto.getElderFamilyDtoList()));
        checkInMapper.insert(checkIn);
        return checkIn;
    }

    /****
     * 新增签约办理
     * @param checkInApplyDto
     * @param elder
     */
    private void insertContract(CheckInApplyDto checkInApplyDto, Elder elder) {
        Contract contract = new Contract();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInContractDto(),contract);
        contract.setElderId(elder.getId().intValue());//老人id
        contract.setContractNumber("HT"+ CodeGenerator.generateContractNumber());//合同编号
        contract.setElderName(elder.getName());
        contract.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
        contract.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
        contract.setStatus(1);
        contractMapper.insert(contract);
    }

    /***
     * 新增或修改老人信息
     * @param checkInApplyDto
     * @param elder
     * @param bed
     * @return
     */
    private Elder insertOrUpdate(CheckInApplyDto checkInApplyDto, Elder elder, Bed bed) {
        if (elder == null) {
            elder = new Elder();
            extracted(checkInApplyDto, elder, bed);
            elderMapper.insert(elder);
        }else{
            extracted(checkInApplyDto, elder, bed);
            elderMapper.updateById(elder);
        }
        return elder;
    }

    /***
     * 处理老人信息的对象注入
     * @param checkInApplyDto
     * @param elder
     * @param bed
     */
    private static void extracted(CheckInApplyDto checkInApplyDto, Elder elder, Bed bed) {
        BeanUtils.copyProperties(checkInApplyDto.getCheckInElderDto(), elder);
        elder.setCreateTime(new Date());
        elder.setBedId(bed.getId());
        elder.setBedNumber(bed.getBedNumber());
    }

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        checkIn.setCreateTime(DateUtils.getNowDate());
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        checkIn.setUpdateTime(DateUtils.getNowDate());
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return checkInMapper.deleteByIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return checkInMapper.deleteById(id);
    }


}
